<template>
  <div class="drawe-container">
    <el-row :gutter="20">
      <el-form ref="requestParams"
               :model="requestParams"
               :rules="rules"
               :disabled="$route.query.type=='detail'"
               label-width="180px">
        <el-col :span="12">
          <el-form-item label="选择项目"
                        prop="project_id">
            <el-select v-model="requestParams.project_id"
                       @change="onProChange"
                       class="common-style"
                       placeholder="请选择">
              <el-option v-for="item in projectArr"
                         :key="item.project_id"
                         :label="item.project_name"
                         :value="item.project_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业">
            <el-input v-model="requestParams.paper_major"
                      placeholder="请输入专业"></el-input>
          </el-form-item>
          <el-form-item label="图纸类型"
                        prop="paper_type">
            <el-select v-model="requestParams.paper_type"
                       class="common-style"
                       placeholder="请选择">
              <el-option v-for="item in draweTypeArr"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="版本号"
                        prop="project_paper_version">
            <div class="version-box-style">
              <el-select v-model="requestParams.project_paper_version"
                         class="common-style"
                         placeholder="请选择">
                <el-option v-for="item in versionArr"
                           :key="item.project_paper_version_id"
                           :label="item.name"
                           :value="item.name">
                </el-option>
              </el-select>
              <el-button :type="addBtnStatus()?'info':'primary'"
                         @click="onAddVer"
                         :disabled="addBtnStatus()?true:false"
                         class="add-style">新增</el-button>
            </div>
          </el-form-item>
          <el-form-item label="WBS（项目设计与分解）">
            <el-cascader :options="wbsCascaderArr"
                         class="common-style"
                         :disabled="requestParams.paper_type==''?true:false"
                         @change="onWbsChange"
                         v-model="requestParams.resolve_wbs_json"
                         :props="propsParam"
                         clearable></el-cascader>
          </el-form-item>
          <el-form-item label="上传图纸">
            <el-upload class="company-logo-upload"
                       ref="uploadFile"
                       :http-request="uploadFileDrawe"
                       action
                       :disabled="getUploadPaperStatus()"
                       :show-file-list="false"
                       :limit="limitNum"
                       :multiple="true"
                       :auto-upload="false"
                       :file-list="fileList"
                       :on-success="handleFileSuccess"
                       :on-change="handleFileChange"
                       :before-remove="beforeRemove"
                       :on-exceed="handleFileExceed"
                       :before-upload="beforeFileUpload">
              <el-button class="upload"
                         size="small"
                         icon="el-icon-top"
                         :disabled="getUploadPaperStatus()?true:false"
                         :type="getUploadPaperStatus()?'info':'primary'">点击上传</el-button>
            </el-upload>
            <ul class="ul-style">
              <li v-for="(item,i) in uploadDraweArr"
                  :key="i">
                <p>{{item.name}}</p>
                <p>
                  <el-button type="text"
                             :disabled="$route.query.type=='detail'?true:false"
                             @click="onDelPaper(item,i)">x</el-button>
                </p>
              </li>
            </ul>
          </el-form-item>
        </el-col>
      </el-form>
      <el-col :span="24"
              class="bottom-box">
        <el-button type="primary"
                   v-if="$route.query.type=='detail'?false:true"
                   @click="onSure('requestParams')">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-col>
      <!-- 上传的个数 -->
      <el-dialog :title="'正在上传(' + uploadFileIndex + '/' + uploadQuene.length + ')'"
                 :modal="mode === 'edit'"
                 width="70%"
                 @close="uploadDialogClose"
                 :visible.sync="uploadQueneDialogVisible">

        <ul class="upload-quene-list">
          <li class="upload-quene-item"
              v-for="(item, index) in uploadQuene"
              :key="index">
            <span class="file-name">
              <img src="@/assets/file-icon.png"
                   alt="" />
              <i>{{ item.name }}</i>
            </span>
            <span class="file-size">{{ item.file_size }}</span>
            <!-- <span class="dir-name">{{ choosedTreeNode.dir_name }}</span> -->
            <span v-if="item.status !== 'resolve'"
                  class="staus">{{
            item.percent
          }}</span>
            <span class="status"
                  v-if="item.status === 'resolve'">
              <i class="fa fa-check-circle"></i>
            </span>
            <!-- 进度条 -->
            <el-progress class="progress"
                         v-if="progressFlag"
                         :percentage="item.loadProgress"></el-progress>
          </li>
        </ul>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="closeDialog"
                     type="primary">确 定</el-button>
        </div>
      </el-dialog>
      <AddVersionDialog v-if="versionVisible==true"
                        :objRow.sync="objRow"
                        :catchBackFunc="catchBackFunc"
                        :versionVisible.sync="versionVisible"></AddVersionDialog>
    </el-row>
  </div>
</template>

<script>
import OSS from 'ali-oss';
import { standardCodeApi } from '@/services/StandardCode';
import { ProjectListApi, draweManagementApi, projectDecomApi, ProDesignDecomApi } from "@/services/ProjectCenter";
import AddVersionDialog from './components/AddVersionDialog';//新增版本号
export default {
  components: {
    AddVersionDialog,//新增版本号
  },
  data () {
    return {
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      objRow: {},
      propsParam: {//级联
        // multiple: true,
        checkStrictly: true,
        value: 'resolve_wbs_id',//匹配响应数据中的id
        label: 'wbs_name',
        children: 'children',
      },
      limitNum: 20,//默认上传的个数最大为20
      uploadDraweArr: [],//已上传的图纸
      mode: 'edit',//编辑
      fileList: [],
      timerId: 0,
      // 当前选中文件树节点
      choosedTreeNode: {},
      uploadQueneDialogVisible: false,
      // 等待上传文件列表
      uploadQuene: [],
      // 当前上传文件在列表中的index
      uploadFileIndex: 0,
      versionVisible: false,//新增版本号弹框默认不显示
      fileList: [],//上传的文件列表
      wbsArr: [],//wbs
      versionArr: [],//版本
      projectArr: [],//项目列表
      draweTypeArr: [],//图纸类型
      rules: {
        project_id: [
          { required: true, message: '选择项目不能为空', trigger: ['blur', 'change'] }
        ],
        project_paper_version: [
          { required: true, message: '版本号不能为空', trigger: ['blur', 'change'] }
        ],
        paper_type: [
          { required: true, message: '选择项目不能为空', trigger: ['blur', 'change'] }
        ]
      },
      requestParams: {
        project_id: '',//项目主键值
        paper_type: '',//图纸类型
        project_paper_version: '',//版本
        paper_major: '',//专业
        paper_pic_url: [],//图纸列表
        resolve_wbs_json: [],
        resolve_wbs_id: '',
      },
      wbsCascaderArr: [],//wbs级联下拉数据
    }
  },
  methods: {
    addBtnStatus () {//新增按钮的状态
      let btnStatus = false;
      if (this.requestParams.project_id == '') {
        btnStatus = true;
      } else if (this.$route.query.type == 'detail') {
        btnStatus = true;
      };
      return btnStatus;
    },
    getUploadPaperStatus () {//上传图纸状态
      let status = false;
      let uploadDraweArr = this.uploadDraweArr.length;//已上传图纸的个数
      let isExistType = this.$route.query.type;//编辑或详情时
      if (isExistType == undefined && this.uploadDraweArr.length == 20) {
        status = true;
      } else if (uploadDraweArr == 1 && isExistType && this.limitNum == 1) {//编辑或详情
        status = true;
      };
      return status;
    },
    catchBackFunc (val) {//版本号新增时保存或关闭时触发的事件
      if (val == 'save') {
        this.requestParams.project_paper_version = '';//版本清空
        this.versionArr = [];//版本下拉数据
        let proId = this.requestParams.project_id;
        this.getVerList(proId);//项目下的版本列表
      }
    },
    async onProChange (projectId) {
      this.requestParams.project_paper_version = '';//版本清空
      this.versionArr = [];//版本下拉数据
      this.requestParams.resolve_wbs_json = [];//wbs清空
      this.wbsCascaderArr = [];//wbs级联数据重置
      await this.getVerList(projectId);//版本列表
      await this.getWbsList(projectId);//获取wbs下拉级联数据
    },
    getWbsList (projectId) {//获取wbs级联的下拉数据
      return ProDesignDecomApi.getResTree({
        params: {
          project_id: projectId,//项目的主键值
        }
      }).then((res) => {
        if (res.data) {//存在时执行
          let wbsCascaderAr = res.data[0].children;//项目下的wbs数据
          this.wbsCascaderArr = wbsCascaderAr;
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    onWbsChange (val) {//wbs值改变时触发 
      console.log('级联val=', val)
    },
    getLimitNum () {//获取上传限制的个数
      let isType = this.$route.query.type;
      if (!isType) {
        this.limitNum++;
      } else {
        this.limitNum = 1;//限制为1个
      }
      return this.limitNum;
    },
    onDelPaper (file, i) {//删除当前的图纸
      this.$confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.limitNum = this.getLimitNum();//限制的个数
        this.uploadDraweArr.splice(i, 1);
        this.$message.success('删除成功!');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 上传文件
    uploadFileDrawe (file) {
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: process.env.bucket
      })
      let address = 'platform/drawe/addOrEditDrawe/' + file.file.name
      client
        .multipartUpload(address, file.file, {
          progress: percent => {
            // this.$set(this.uploadQuene[this.uploadFileIndex], 'percent', parseInt(percent * 100) + '%')
            this.uploadQuene[this.uploadFileIndex].percent =
              parseInt(percent * 100) + '%'
            this.uploadQuene[this.uploadFileIndex].loadProgress = parseInt(percent * 100)
          }
        })
        .then(res => {
          // data.attach = 'http://dev-consult.oss-cn-hangzhou.aliyuncs.com/' + res.name
          this.uploadQuene[this.uploadFileIndex].status = 'resolve'
          this.uploadQuene[this.uploadFileIndex].file_address = res.res.requestUrls[0].split('?')[0]
          this.uploadFileIndex++
          //全部上传完毕后隐藏进度条
          if (this.uploadFileIndex === this.uploadQuene.length) {
            setTimeout(() => { this.progressFlag = false }, 1000) // 一秒后关闭进度条
          }
          this.uploadFileQuene();//队列
          // this.fileList = this.uploadQuene
        })
    },
    // 上传成功时的钩子函数
    handleFileSuccess (response, file, fileList) {
      console.log('上传成功response, file, fileList=', response, file, fileList)
    },
    // 通过队列的方式上传
    uploadFileQuene () {
      if (this.uploadFileIndex < this.uploadQuene.length) {
        this.uploadQuene[this.uploadFileIndex].status = 'ready'
        this.$refs.uploadFile.submit();
      }
    },
    handleFileChange (file, filelist) {
      this.progressFlag = true; // 显示进度条
      // if (this.choosedTreeNode.p_project_dir_id) {
      // 简易版debounce，以最后一次为准
      clearTimeout(this.timerId);//清空延时器
      this.timerId = setTimeout(() => {
        // elementui 上传组件会把filelist中所有status为ready的数据上传，
        // 因此首先把所有数据的status置为waiting，然后依次把status置为ready，实现队列效果
        filelist.map(item => {
          item.file_alias = item.name
          item.file_ext = item.name.split('.')[1]
          item.file_size = (item.size / (1024 * 1024)).toFixed(2) + 'M'
          item.status = 'waiting'
          this.$set(item, 'percent', '0%')
        })
        this.uploadQuene = filelist
        this.uploadFileIndex = 0
        this.uploadQueneDialogVisible = true
        // 控制文件一个个上传
        this.uploadFileQuene()
      }, 300)
      // } else {
      //   this.$message.warning('请选择文件夹')
      // }
    },
    beforeFileUpload (file, fileList) {
      console.log('上传前的钩子函数', file, fileList, 'before upload')
    },
    getFileArr (file) {//获取上传文件的总个数
      let arr = [];//文件
      for (var i of file) {
        arr.push(i)
      };
      return arr;//文件的总个数
    },
    beforeRemove (file, fileList) {//删除前确认
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件超出数量限制钩子函数
    handleFileExceed (files, fileList) {
      let selectFileNum = this.uploadDraweArr.length;//已选中的个数
      this.$message.warning(`当前限制选择 20 个文件，本次选择了 ${files.length} 个文件，共有了 ${files.length + fileList.length + selectFileNum} 个文件`);
      // if (this.getFileArr(file).length > 5) {//最多允许上传5个文件
      //   this.$message.warning('最多同时上传5个文件')
      // }
    },
    // 关闭上传文件弹框,清空队列,调用文件列表新增接口
    closeDialog () {
      let newUploadLength = this.uploadQuene.length;
      let oldUploadLength = this.uploadDraweArr.length;
      let allLength = newUploadLength + oldUploadLength;
      if (allLength > 20) {//个数不能超过最大限制5
        this.$message.warning(`当前限制选择 20 个文件，本次选择了 ${newUploadLength} 个文件，共选择了 ${allLength} 个文件`);
      } else {//个数不超过限制时执行
        if (this.uploadQuene.length > 0) {
          this.uploadQuene.map((item, ind, arr) => {
            this.uploadDraweArr.push(item)
          })
        };
        let isExistType = this.$route.query.type;
        if (isExistType == 'edit') {
          this.limitNum = 1;//默认为上传最大个数为1
        } else {
          this.limitNum = 20 - this.uploadDraweArr.length;//限制最大个数
        }
      }

      this.uploadDraweArr;//连接为一个数组
      // this.uploadFileIndex = 0;
      // this.uploadQuene = []
      // this.createProjectFile()
      // this.$refs.uploadFile.clearFiles();//重置
      this.uploadQueneDialogVisible = false
    },
    // 点击右上角的×关闭时，只清空队列，不调用新增
    uploadDialogClose () {
      this.uploadFileIndex = 0;
      this.uploadQuene = [];//清空
      this.$refs.uploadFile.clearFiles();//重置
      this.uploadQueneDialogVisible = false
    },
    getProList () {//获取项目列表
      return ProjectListApi.getProjectList({
        params: {
          is_page: 0,//不分页
        }
      }).then((res) => {
        if (res.data) {
          this.projectArr = res.data.list;
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    onAddVer () {//新增版本
      this.$set(this.objRow, 'project_id', this.requestParams.project_id);
      this.versionVisible = true;
    },
    onCancel () {//取消
      this.requestParams = this.$options.data().requestParams;//重置
      history.back(-1);//返回上一个页面
    },
    getPaperList () {//获取图纸的列表数据
      let paperArr = [];
      if (this.uploadDraweArr.length > 0) {
        this.uploadDraweArr.map((item, ind, arr) => {
          paperArr.push({
            name: item.file_alias,//图纸的名称
            url: item.file_address//url
          })
        })
      };
      return paperArr;
    },
    getUploadDrawe () {//编辑的时候，图纸对象值
      let obj = {};
      let name = this.uploadDraweArr[0].name;
      let url = this.uploadDraweArr[0].url || this.uploadDraweArr[0].file_address;
      obj = {
        name: name,
        url: url,
      };
      return obj;
    },
    getWbsId (wbsArr) {//当前wbs的主键值
      let wbsId = '';
      if (wbsArr.length > 0 && Array.isArray(wbsArr)) {
        wbsId = wbsArr.join(',')
      }
      return wbsId;
    },
    getParams () {//参数
      let obj = {};
      let paperType = this.requestParams.paper_type;
      obj = Object.assign(this.requestParams);
      obj.paper_pic_url = this.getPaperList();//获取图纸的列表
      let resolveWbsArrLength = obj.resolve_wbs_json.length - 1;
      obj.resolve_wbs_id = obj.resolve_wbs_json[resolveWbsArrLength];
      obj.resolve_wbs_json = this.getWbsId(obj.resolve_wbs_json);//当前wbs的主键值
      let paperId = this.$route.query.paper_id;//图纸主键值
      if (this.$route.query.type == 'edit') {
        this.$set(obj, 'paper_id', paperId);
        this.$set(obj, 'type', paperType);
        if (this.uploadDraweArr.length > 0) {
          this.$set(obj, 'paper_pic_url', this.getUploadDrawe());
        };
        this.$delete(obj, 'pic_url');
      };

      return obj;
    },
    //批量创建图纸
    createBatchPaper () {
      draweManagementApi.addPaper({
        data: this.getParams()//参数
      }).then(res => {
        if (res.code == 0) {
          this.$message.success('操作成功');
          history.back(-1);//返回上一个页面
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    editPaper () {//编辑
      draweManagementApi.editPaper({
        data: this.getParams()//参数
      }).then(res => {
        if (res.code == 0) {
          this.$message.success('操作成功');
          history.back(-1);//返回上一个页面
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    onSure (data) {//确定
      this.$refs[data].validate((valid) => {
        if (valid) {
          let operaType = this.$route.query.type;
          if (operaType == 'edit') {//编辑
            this.editPaper();//编辑图纸
          } else {//批量创建
            this.createBatchPaper();//批量创建图纸
          }
        } else {
          return false;
        }
      })
    },
    //图片上传事件
    handleRemove (file, fileList) {
    },
    handleAvatarSuccess (res, file) {
      this.form.imageUrl = URL.createObjectURL(file.raw);
    },
    handlePreview (file) {
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //上传图纸
    addUploadPictrue (data) {
      var _this = this;
      var oss_region = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: _this.image_Url,
      });
      var c = new Date().getMonth() + parseInt(1);
      if (c >= 10) {

      } else {
        c = '0' + c;
      }
      var path = 'upload/images/admin_avatar/' + new Date().getFullYear() + c + new Date().getDate() + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + data.file.name.substring(data.file.name.length - 4);

      oss_region.multipartUpload(path, data.file, {

      }).then((res) => {
        //图片路径
        if (res.res.requestUrls[0].indexOf("?") != -1) {
          _this.iops = res.res.requestUrls[0].indexOf("?");
          _this.form.imageUrl = res.res.requestUrls[0].substring(0, _this.iops);
        } else {
          _this.form.imageUrl = res.res.requestUrls[0];
        }
        _this.form.imageUrl_relative = (res.name).substr(7);
        _this.form.pictrue_daxiao = Math.round(data.file.size / 1024 / 1024) + 'M';
      }).catch((err) => {
        console.log(err)
      });
    },
    getVerList (projectId) {//获取版本列表数据
      return draweManagementApi.getVerList({
        params: {
          project_id: projectId,
          is_page: 0,
        }
      }).then((res) => {
        if (res.data) {
          this.versionArr = res.data.list;
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取图纸类型标准码
    getPaperTypeCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'paperType',//图纸类型
        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.draweTypeArr = res.data.list
          window.localStorage.setItem('platformPaperType', JSON.stringify(this.draweTypeArr))
        }
      }, err => {
        console.log(err)
      })
    },
    getDataTypeChange (dataArr) {//数据类型转换（字符串转为数值型）
      let arr = [];
      dataArr.map((item) => {
        arr.push(Number(item))
      });
      return arr;
    },
    getResolWbsJson (str) {//wbs回显的值
      let wbsArr = [];
      if (str != '') {
        wbsArr = this.getDataTypeChange(str.split(','));//数据类型转换
      }
      return wbsArr;
    },
    getPaperInfo () {//获取当前图纸的信息  
      let paperId = this.$route.query.paper_id;//图纸主键值
      draweManagementApi.getPaperInfo({
        params: {
          paper_id: paperId,//图纸的主键值
        }
      }).then((res) => {
        let resolve_wbs_json = res.data.resolve_wbs_json;
        let url = res.data.pic_url;
        let name = res.data.name;
        // let paperType = res.data.type;//图纸类型
        let projectId = res.data.project_id;//项目主键值
        this.onProChange(projectId);
        this.requestParams = res.data;
        // this.requestParams.paper_type = paperType;//图纸类型
        this.$set(this.requestParams, 'paper_type', res.data.type)
        this.requestParams.resolve_wbs_json = this.getResolWbsJson(resolve_wbs_json);//wbs回显
        // this.requestParams.paper_major = res.data.major;
        this.$set(this.requestParams, 'paper_major', res.data.major) //专业和图纸类型赋值后不能改变问题
        this.uploadDraweArr.push({
          name: name,
          url: url
        })
      }).catch((error) => {
        console.log(error)
      })
    }
  },
  async created () {
    let platformPaperType = window.localStorage.getItem('platformPaperType')
    if (platformPaperType) {
      this.draweTypeArr = JSON.parse(platformPaperType)
    } else {
      await this.getPaperTypeCode();//图纸类型
    };
    await this.getProList();//项目列表
    let operaType = this.$route.query.type;//当前操作的类型
    if (operaType) {
      this.limitNum = 1;//详情或编辑时最大限制是1
      this.getPaperInfo();//获取图纸的详情
    }
  }
}
</script>

<style lang="scss" scoped>
.ul-style {
  margin-top: 20px;
  li {
    width: 100%;
    padding: 0px 10px 0px 0px;
    height: 36px;
    line-height: 36px;
    display: flex;
    flex-direction: row;
    justify-content: space-between !important;
    p {
      width: 60px;
      text-align: right;
    }
  }
  li:hover {
    // cursor: pointer;
    background-color: #eeeeee;
  }
  li p:nth-child(2) {
    span {
      cursor: pointer;
    }
  }
}
.ul-style li p:nth-child(1) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 60px);
  display: flex;
}
.upload-quene-list {
  .upload-quene-item {
    width: 100%;
    height: 48px;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding-left: 40px;
    font-size: 14px;
    color: #666;

    &:first-child {
      border-top: 1px solid #e5e5e5;
    }
    .progress {
      width: 400px;
    }
    .file-name {
      width: 260px;
      margin-right: 120px;
      display: flex;
      align-items: center;
      img {
        width: 24px;
        height: 24px;
        margin-right: 15px;
      }
    }

    .file-size {
      width: 60px;
      margin-right: 40px;
    }

    .dir-name {
      width: 100px;
      margin-right: 40px;
      color: #1890ff;
    }

    .status {
      color: #333;
      display: flex;
      align-items: center;

      i {
        color: #52c41a;
        margin-right: 8px;
      }
    }
  }
}
.drawe-container {
  padding: 20px;
  .version-box-style {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .common-style {
    width: 100%;
  }
  .add-style {
    margin-left: 20px;
  }
  .bottom-box {
    text-align: center;
  }
}
</style>